package com.guojiang.guoaicodemother.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.guojiang.guoaicodemother.exception.ErrorCode;
import com.guojiang.guoaicodemother.exception.ThrowUtils;
import com.guojiang.guoaicodemother.manager.CosManager;
import com.guojiang.guoaicodemother.service.ScreenshotService;
import com.guojiang.guoaicodemother.utils.WebScreenshotUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 截图 服务实现层。
 */
@Service
@Slf4j
public class ScreenshotServiceImpl implements ScreenshotService {

    @Resource
    private CosManager cosManager;

    /**
     * 通用截图服务
     *
     * @param webUrl
     * @return 可访问的图片地址
     */
    @Override
    public String generateAndUploadScreenshot(String webUrl) {
        // 本地截图，得到本地文件路径
        String localScreenshotPath = WebScreenshotUtils.saveWebScreenshot(webUrl);
        // uploadScreenshotToCOS 没有抛出异常，所以这里外层需要处理一下
        ThrowUtils.throwIf(StrUtil.isBlank(localScreenshotPath), ErrorCode.SYSTEM_ERROR, "生成网页截图失败");
        // 上传到 COS
        try {
            String cosUrl = uploadScreenshotToCOS(localScreenshotPath);
            ThrowUtils.throwIf(StrUtil.isBlank(cosUrl), ErrorCode.SYSTEM_ERROR, "上传截图到 COS 失败");
            log.info("截图上传成功，URL：{}", cosUrl);
            clearLocalFile(localScreenshotPath);
            return cosUrl;
        } finally {
            // 清理本地文件
            clearLocalFile(localScreenshotPath);
        }
    }

    /**
     * 上传本地截图到 COS
     *
     * @param localScreenshotPath
     * @return
     */
    private String uploadScreenshotToCOS(String localScreenshotPath) {
        if (StrUtil.isBlank(localScreenshotPath)) {
            log.error("上传失败，本地截图路径为空");
            return null;
        }
        File screenshotFile = new File(localScreenshotPath);
        if (!screenshotFile.exists()) {
            log.error("上传失败，本地截图文件不存在");
            return null;
        }

        String fileName = UUID.randomUUID().toString().substring(0, 8) + "_compressed.jpg";
        // 生成 COS 对象键值
        String cosKey = generateCOSKey(fileName);
        return cosManager.uploadFileAndReturnUrl(cosKey, screenshotFile);
    }


    /**
     * 根据本地截图文件名生成 COS 对象键值
     *
     * @param fileName
     * @return
     */
    private String generateCOSKey(String fileName) {
        String dataPath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd/HH"));
        // /screenshot/2025/08/11/15/UUID0-8_compressed.jpg
        return String.format("/screenshot/%s/%s", dataPath, fileName);
    }

    /**
     * 清理本地文件
     *
     * @return
     */
    private void clearLocalFile(String localScreenshotPath) {
        boolean delResult = FileUtil.del(localScreenshotPath);
        if (!delResult) {
            log.error("清理本地文件失败，本地文件路径是：{}", localScreenshotPath);
        }
        log.error("清理本地文件 {} 成功", localScreenshotPath);
    }
}
